/*
 * transaction.c
 *
 *   Copyright 2010 Emediate ApS
 *
 *   This file is part of Stampede.
 *
 *   Stampede is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   Stampede is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with Stampede.  If not, see <http://www.gnu.org/licenses/>.
 *
 *   Written by: Erland Lewin <erland@emediate.se>
 *
 *  Created on: Dec 22, 2009
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <libxml/xmlstring.h>

#include "transaction.h"

typedef struct sTransaction
{
   xmlChar *url;
   xmlChar *expectedBodyUTF8;
   int thinkTimeSeconds;
} sTransaction;

Transaction transaction_create( const xmlChar *url, int thinkTimeSeconds,
                                const xmlChar *expectedBodyFilename )
{
   Transaction transaction;

   transaction = malloc( sizeof( sTransaction ));

   transaction->url = (xmlChar *) strdup( (char *) url );
   transaction->thinkTimeSeconds = thinkTimeSeconds;

   if( expectedBodyFilename == NULL )
      transaction->expectedBodyUTF8 = NULL;
   else
   {
      FILE *file;
      struct stat statX;
      int result;

      result = stat( (char *) expectedBodyFilename, &statX );
      if( result != 0 )
      {
         fprintf( stderr, "Error reading expected body file '%s'", expectedBodyFilename );
         perror( ": " );
         return NULL;
      }

      file = fopen( (char *) expectedBodyFilename, "r" );
      transaction->expectedBodyUTF8 = malloc( statX.st_size );

      result = fread( transaction->expectedBodyUTF8, statX.st_size, 1, file );
      if( result != 1 )
      {
         perror( "read of expectedBodyFilename failed: " );
         fclose( file );

         return NULL;
      }

      fclose( file );
   }


   return transaction;
}

const xmlChar *transaction_getExpectedBody( const Transaction transaction )
{
   return transaction->expectedBodyUTF8;
}

const xmlChar *transaction_getURL( const Transaction transaction )
{
   return transaction->url;
}

int transaction_getThinkTime( const Transaction transaction )
{
   return transaction->thinkTimeSeconds;
}
